import { getBuffetOrderDetail } from "@/api";
import { sleep } from "@kingon/app-tools";
// 轮询查询订单状态 (用于固定消费的扫码支付，目前固定消费接口融合下单和支付，故需要额外处理)
export const loopCheckOrderStatus = async (orderId: string) => {
  const maxFach = 10;
  const maxUseTimeLimit = 30 * 1000;
  const startTime = new Date().getTime();
  let useTime = 0;
  let fachCount = 0;
  let isPaySuccess = false;
  const getOrderDetails = async () => {
    try {
      const { data } = await getBuffetOrderDetail({
        buffetOrderId: orderId,
      });
      // payStatus	支付状态（0未支付 1已支付）
      return data?.payStatus == 1;
    } catch (error) {
      return false;
    }
  };
  // 进行 maxFach 次的轮询， 时间在 maxUseTimeLimit 内， 
  // 如果超过时间或者查询成功则结束轮询
  while (fachCount < maxFach) {
    isPaySuccess = await getOrderDetails();
    if (isPaySuccess) {
      break;
    }
    fachCount++;
    await sleep(2000);
    if (new Date().getTime() - startTime > maxUseTimeLimit) {
      break;
    }
  }

  useTime = new Date().getTime() - startTime;
  if (!isPaySuccess) {
    if (fachCount >= maxFach || useTime > maxUseTimeLimit) {
      throw new Error("订单查询超时 或 支付超时");
    } else {
      throw new Error("订单未支付");
    }
  }
};